# views 路由 + 视图函数
import datetime

from flask import Blueprint, render_template, request, redirect, session

# 蓝图 需要到__init__.py当中绑定blue
blue = Blueprint('user', __name__)


# 会话技术
# cookie和session
@blue.route('/')
@blue.route('/home/')
def index():
    # 4. 获取cookie
    # username = request.cookies.get('user')

    # 获取session
    username = session.get('user')

    if username:
        return render_template('home.html', username=username)
    else:
        return redirect('/login/')


@blue.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    elif request.method == 'POST':
        pass
        # return 'POST'

        # 1. 获取前端提交过来的数据
        # username = request.form['username']
        # password = request.form['password']
        username = request.form.get('username')
        password = request.form.get('password')

        # 2. 判断数据
        if username == 'admin' and password == '123456':
            # 登录成功
            response = redirect('/home/')
            # 3. 设置cookie 不能用中文
            # 默认浏览器关闭则cookie失效
            # 过期时间，max_age 秒为单位
            # expires： 指定时间datetime日期
            # response.set_cookie('user', username, max_age=3600*24*7)
            # response.set_cookie('user', username, expires=datetime.datetime(2025, 12, 12))

            # 设置session
            session['user'] = username
            # 设置sesion有效时间
            session.permanent = True

            return response
        else:
            # 登录失败
            return "用户名或密码错误"

# 注销
@blue.route('/logout/')
def logout():
    response = redirect('/home/')
    # 5. 删除cookie
    # response.delete_cookie('user')

    # 删除session
    session.pop('user', None)
    # session.clear()  # 谨慎使用，会删除服务器所以session内容

    return response

